<template>
  <div>
    <el-upload
      :class="{disabled: disabled}"
      action="#"
      :file-list="fileList"
      :on-remove="onRemove"
      :on-change="onChange"
      :on-preview="onPreview"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
      list-type="picture-card"
    >
      <i class="el-icon-plus"/>
    </el-upload>
    <el-dialog title="图片预览" :visible.sync="dialogShow">
      <img :src="imgUrl" alt="" style="width: 100%">
    </el-dialog>
    <el-progress v-if="percentageShow" :percentage="percentageNum"/>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

const cos = new COS({
  SecretId: 'AKIDDIDuUs45tNdmhPuCHC2kXGwQhy3xrhQ1', // 身份识别 ID
  SecretKey: 'QddXKvNirnYCeyBJJ7lJiy2udAUcaN2V' // 身份密钥
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      fileList: [],
      dialogShow: false,
      imgUrl: '',
      currentUid: '',
      percentageNum: 0,
      percentageShow: false
    }
  },
  computed: {
    disabled() {
      return this.fileList.length === 1
    }
  },
  methods: {
    // 移除图片时触发
    onRemove(file, fileList) {
      console.log(file, fileList)
      this.fileList = fileList
    },
    // fileList发生改变时触发
    onChange(file, fileList) {
      console.log(JSON.stringify(file))
      this.fileList = fileList
    },
    // 图片预览
    onPreview(file) {
      console.log(file)
      this.dialogShow = true
      this.imgUrl = file.url
    },
    // 上传成功之前的钩子
    beforeUpload(file) {
      // 格式校验
      const typeArr = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']
      if (!typeArr.includes(file.type)) {
        this.$message.error('上传头像图片格式不正确!')
      }
      // 体积校验
      if (file.size > 1024 * 1024 * 2) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.currentUid = file.uid
      this.percentageShow = true
      return true
    },
    // 覆盖上传图片行为的钩子
    httpRequest(data) {
      console.log(data)
      cos.putObject({
        Bucket: 'chenzhe968-1257713262', // 存储桶
        Region: 'ap-nanjing', // 地域
        Key: data.file.name, // 文件名
        Body: data.file, // 要上传的文件对象
        // StorageClass: 'STANDARD' // 上传的模式类型 直接默认 标准模式即可
        onProgress: (info) => {
          console.log(JSON.stringify(info))
          this.percentageNum = parseInt(info.percent * 100)
        }
        // 上传到腾讯云 =》 哪个存储桶 哪个地域的存储桶 文件  格式  名称 回调
      }, (err, data) => {
        // data返回数据之后 应该如何处理
        if (err) return this.$message.error('上传失败')
        console.log(err || data)
        this.fileList.map(item => {
          if (item.uid === this.currentUid) {
            item.url = 'http://' + data.Location
            item.uploaded = true
          }
          return item
        })
      })
      setTimeout(() => {
        this.percentageShow = false
        this.percentageNum = 0
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
